package com.distribution.system.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.dto.AgentAddDto;
import com.distribution.system.domain.dto.AgentDTO;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.openapi.domain.entity.CmccDaDownChannelInfo;
import com.distribution.system.openapi.domain.req.CmccDaDownChannelInfoAddReq;
import com.distribution.system.openapi.domain.req.CmccDaDownChannelInfoListReq;
import com.distribution.system.openapi.domain.req.CmccDaDownChannelInfoUpdateReq;
import com.distribution.system.openapi.service.CmccDaDownChannelInfoService;
import com.distribution.system.service.AgentManageService;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: GodLu
 * @create: 2024-07-09 10:46
 * @description: 合作方信息控制器
 */
@Validated
@Slf4j
@RestController
@RequestMapping("/CmccDaDownChannelInfo")
public class CmccDaDownChannelInfoController extends BaseController {
    @Resource
    private CmccDaDownChannelInfoService cmccDaDownChannelInfoService;
    @Resource
    AgentManageService agentManageService;
    @Resource
    SysUserMapper sysUserMapper;

    /**
    * @Author: GodLu
    * @Date: 2024/7/9 14:41
    * @Description: 查询下游渠道信息列表
    * @param cmccDaDownChannelInfoListReq 请求信息
    * @return: TableDataInfo
    */
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody CmccDaDownChannelInfoListReq cmccDaDownChannelInfoListReq) {
        startPage();
        LambdaQueryWrapper<CmccDaDownChannelInfo> queryWrapper = new LambdaQueryWrapper<CmccDaDownChannelInfo>()
                .eq(!Objects.isNull(cmccDaDownChannelInfoListReq.getUserId()), CmccDaDownChannelInfo::getUserId, cmccDaDownChannelInfoListReq.getUserId())
                .like(!StringUtils.isEmpty(cmccDaDownChannelInfoListReq.getChannelName()), CmccDaDownChannelInfo::getChannelName, cmccDaDownChannelInfoListReq.getChannelName())
                .eq(!Objects.isNull(cmccDaDownChannelInfoListReq.getAppId()), CmccDaDownChannelInfo::getAppId, cmccDaDownChannelInfoListReq.getAppId())
                .eq(!Objects.isNull(cmccDaDownChannelInfoListReq.getStatus()), CmccDaDownChannelInfo::getStatus, cmccDaDownChannelInfoListReq.getStatus());
        if (!Objects.isNull(cmccDaDownChannelInfoListReq.getBeginTime())) {
            queryWrapper.ge(CmccDaDownChannelInfo::getCreateTime, cmccDaDownChannelInfoListReq.getBeginTime());
        }
        if (!Objects.isNull(cmccDaDownChannelInfoListReq.getEndTime())) {
            queryWrapper.le(CmccDaDownChannelInfo::getCreateTime,cmccDaDownChannelInfoListReq.getEndTime());
        }
        // 没有注销
        queryWrapper.ne(CmccDaDownChannelInfo::getDelFlag,"2");
        queryWrapper.orderByDesc(CmccDaDownChannelInfo::getCreateTime);
        List<CmccDaDownChannelInfo> CmccDaDownChannelInfoList = cmccDaDownChannelInfoService.list(queryWrapper);
        return getDataTable(CmccDaDownChannelInfoList);
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody @Valid CmccDaDownChannelInfoAddReq cmccDaDownChannelInfoAddReq) {
//        System.out.println("cmccDaDownChannelInfoAddReq = " + cmccDaDownChannelInfoAddReq);
        CmccDaDownChannelInfo cmccDaDownChannelInfo = new CmccDaDownChannelInfo();
        BeanUtils.copyBean(cmccDaDownChannelInfoAddReq, cmccDaDownChannelInfo);
        // 新建代理
        AgentAddDto agentAddDto = new AgentAddDto();
        agentAddDto.setUserName(cmccDaDownChannelInfoAddReq.getUserName());
        agentAddDto.setNickName(cmccDaDownChannelInfoAddReq.getChannelName());
        agentAddDto.setParentId(getUserId());
        agentManageService.addAgent(agentAddDto);
        // 查询新增用户信息
        SysUser sysUser = sysUserMapper.selectUserByUserName(agentAddDto.getUserName());
        cmccDaDownChannelInfo.setUserId(sysUser.getUserId().intValue());
        cmccDaDownChannelInfo.setUserName(sysUser.getUserName());
        // 接口信息
        String appid = IdUtil.getSnowflakeNextIdStr();
        cmccDaDownChannelInfo.setAppId(appid.substring(appid.length() - 9,appid.length()-1));
        cmccDaDownChannelInfo.setAppSecret(RandomUtil.randomString(20));
        // 创建更新时间
        cmccDaDownChannelInfo.setCreateTime(LocalDateTime.now());
        cmccDaDownChannelInfo.setUpdateTime(LocalDateTime.now());
        // 删除标记
        cmccDaDownChannelInfo.setDelFlag("0");
        // 保存
        cmccDaDownChannelInfoService.save(cmccDaDownChannelInfo);
        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/getById")
    public AjaxResult getById(@RequestBody String id) {
        List<CmccDaDownChannelInfo> cmccDaDownChannelInfoList = cmccDaDownChannelInfoService
                .list(new LambdaQueryWrapper<CmccDaDownChannelInfo>().eq(CmccDaDownChannelInfo::getId,id));
        // 如果不存在则报错
        if (cmccDaDownChannelInfoList == null || cmccDaDownChannelInfoList.isEmpty()) return error("查询不到合作方信息");
        // 如果存在多条记录则bug，联系管理员
        if (cmccDaDownChannelInfoList.size() > 1) return error("当前ID存在多条记录，请联系系统管理员解决");
        return success(cmccDaDownChannelInfoList.get(0));
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody @Validated CmccDaDownChannelInfoUpdateReq cmccDaDownChannelInfoUpdateReq) {
        System.out.println("cmccDaDownChannelInfoUpdateReq = " + cmccDaDownChannelInfoUpdateReq);
        CmccDaDownChannelInfo cmccDaDownChannelInfo = new CmccDaDownChannelInfo();
        BeanUtils.copyBean(cmccDaDownChannelInfoUpdateReq, cmccDaDownChannelInfo);
        cmccDaDownChannelInfoService.update(cmccDaDownChannelInfo,
                new LambdaUpdateWrapper<CmccDaDownChannelInfo>().eq(CmccDaDownChannelInfo::getId,cmccDaDownChannelInfo.getId()));
        return success();
    }

    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/del")
    public AjaxResult del(@RequestBody @NotNull Integer id) {
        // 查找当前合作方信息记录
        List<CmccDaDownChannelInfo> cmccDaDownChannelInfoList = cmccDaDownChannelInfoService.list(new LambdaQueryWrapper<CmccDaDownChannelInfo>().eq(CmccDaDownChannelInfo::getId, id));
        if (cmccDaDownChannelInfoList == null || cmccDaDownChannelInfoList.isEmpty()) return error("未查到当前合作方信息");
        if (cmccDaDownChannelInfoList.size() > 1) return error("存在多条记录，请联系系统管理员");
        CmccDaDownChannelInfo cmccDaDownChannelInfo = cmccDaDownChannelInfoList.get(0);
        // 删除绑定的用户信息
        sysUserMapper.deleteUserById(cmccDaDownChannelInfo.getUserId().longValue());
        // 删除三方合作信息
        boolean isSuccess = cmccDaDownChannelInfoService.remove(new LambdaQueryWrapper<CmccDaDownChannelInfo>().eq(CmccDaDownChannelInfo::getId, id));
        return isSuccess ? success() : error("删除失败");
    }
}
